package com.vegetable.common.aspect;

import com.vegetable.common.utils.MessageUtils;
import com.vegetable.modules.entity.sys.SysUserEntity;
import com.vegetable.modules.service.sys.SysUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 消息通知切面
 * 在关键业务操作完成后自动发送消息通知
 *
 * @author Qoder
 */
@Slf4j
//@Aspect
//@Component
@AllArgsConstructor
public class MessageNotificationAspect {

    private final SysUserService sysUserService;

    /**
     * 定义切入点：所有以save、update、delete开头的service方法
     */
    @Pointcut("execution(* com.vegetable.modules.service.*.*.save*(..)) || " +
            "execution(* com.vegetable.modules.service.*.*.update*(..)) || " +
            "execution(* com.vegetable.modules.service.*.*.delete*(..))")
    public void businessOperation() {
    }

    /**
     * 在方法执行后发送消息通知
     */
    @After("businessOperation()")
    public void sendMessageAfterBusinessOperation(JoinPoint joinPoint) {
        try {
            // 获取当前用户
            SysUserEntity currentUser = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
            if (currentUser == null) {
                return;
            }

            // 获取操作类型
            String methodName = joinPoint.getSignature().getName();
            String operationType = getOperationType(methodName);

            // 获取操作对象
            String targetObject = getTargetObject(joinPoint);

            // 构造消息内容
            String title = "系统通知";
            String content = String.format("您在 %s 执行了%s操作，操作对象为：%s", 
                    new Date().toString(), operationType, targetObject);

            // 发送消息给当前用户
            MessageUtils.sendMessage(currentUser.getUserId(), title, content, 2, 0);
        } catch (Exception e) {
            log.error("发送消息通知失败", e);
        }
    }

    /**
     * 根据方法名获取操作类型
     */
    private String getOperationType(String methodName) {
        if (methodName.startsWith("save")) {
            return "新增";
        } else if (methodName.startsWith("update")) {
            return "修改";
        } else if (methodName.startsWith("delete")) {
            return "删除";
        } else {
            return "未知";
        }
    }

    /**
     * 获取操作对象
     */
    private String getTargetObject(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        if (args != null && args.length > 0) {
            Object arg = args[0];
            if (arg != null) {
                return arg.getClass().getSimpleName();
            }
        }
        return "未知对象";
    }
}